import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth.js'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 环境变量配置‌:ml-citation{ref="3,6" data="citationList"}
  timeout: 10000,
})

// 请求拦截器（添加Token）
service.interceptors.request.use(
  (config) => {
    config.api = import.meta.env.VITE_APP_BASE_API
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}` // 鉴权逻辑‌:ml-citation{ref="4,7" data="citationList"}
      config.headers['summary'] = token
    }

    return config
  },
  (error) => Promise.reject(error),
)

// 响应拦截器（统一错误处理）
service.interceptors.response.use(
  (response) => {
    if (
      response.request.responseType === 'blob' ||
      response.request.responseType === 'arraybuffer'
    ) {
      return response.data
    }
    if (response.data.rtnCode === '0005' || response.data.rtnCode === 'QQ0005') {
      removeToken()
      ElMessage.error(response.data.message || '接口错误')
      location.reload(true)
    }
    if (response.data.rtnCode !== '0000') {
      ElMessage.error(response.data.message || '接口错误')
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  (error) => {
    ElMessage.error(response.data.message || '接口错误')
    return Promise.reject(error)
  },
)

export default service
